package com.ytxg.health_management.comment.service;

import com.ytxg.health_management.article.mapper.ArticleMapper;
import com.ytxg.health_management.article.pojo.ArticleMain;
import com.ytxg.health_management.comment.mapper.CommentMapper;
import com.ytxg.health_management.likeRecords.mapper.LikeRecordsMapper;
import com.ytxg.health_management.notice.entity.Notice;
import com.ytxg.health_management.notice.entity.UserNotice;
import com.ytxg.health_management.notice.mapper.NoticeMapper;
import com.ytxg.health_management.pojo.entity.Comments;
import com.ytxg.health_management.likeRecords.entity.LikeRecords;
import com.ytxg.health_management.pojo.entity.Page;
import com.ytxg.health_management.pojo.entity.Result;
import com.ytxg.health_management.util.Const;
import com.ytxg.health_management.util.MyException;
import com.ytxg.health_management.webSocket.WebSocketServer;
import com.ytxg.health_management.webSocket.entity.WebSocketMessage;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class CommentServiceImpl implements CommentService {

    private static final Logger log = LoggerFactory.getLogger(CommentServiceImpl.class);
    @Resource
    CommentMapper commentMapper;
    @Resource
    LikeRecordsMapper likeRecordsMapper;
    @Resource
    NoticeMapper noticeMapper;
    @Resource
    ArticleMapper articleMapper;

    /**
     * 查询文章评论
     */
    @Override
    public Result<List<Comments>> getCommentsByArticleId(Integer articleId) {
        Comments select = new Comments().setArticleId(articleId).setLevel("1");
        List<Comments> comments = commentMapper.selectComments(select);
        return Result.success(comments);
    }
    /**
     * 查询文章评论全
     */
    @Override
    public Result<Map<String, Object>> getCommentsAll(Comments comments) {
        comments.setCurrentPage((comments.getCurrentPage()-1)*comments.getPageSize());
        List<Comments> commentRes = commentMapper.selectCommentsAll(comments);
        int total = commentMapper.selectCounts(comments);
        HashMap<String, Object> res = new HashMap<>();
        res.put("total", total);
        res.put("commentList", commentRes);
        return Result.success(res);
    }

    /**
     * 添加评论
     */
    @Override
    @Transactional
    public Result<String> addComment(Comments comments) {
        //设置文章基础信息
        comments.setLike(0).setDislike(0).setCreateTime(new Date()).setReplyNumber(0);
        //查找文章作者
        List<ArticleMain> article = articleMapper.selectArticleMainBase(new ArticleMain().setId(comments.getArticleId()), new Page());
        //如果是1级评论
        if (Objects.equals(comments.getLevel(), "1")) {

            comments.setReplyUserId(article.get(0).getUserId());
            try {
                log.info("添加1级评论：{}", comments);
                commentMapper.insertComments(comments);
                articleMapper.commentNumberAdd(comments.getArticleId());
            } catch (Exception e) {
                throw new MyException("评论失败,请检查文章是否存在" + e);
            }
        } else {
            commentMapper.updateReplyCount(comments.getReplyId());
            try {
                log.info("添加{}级评论：{}", comments.getLevel(), comments);
                commentMapper.insertComments(comments);
            } catch (Exception e) {
                throw new MyException("评论失败,请检查文章是否存在" + e);
            }
        }
        //发消息
        UserNotice userNotice = noticeMapper.selectUser(comments.getUserId());
        noticeMapper.insertNotice(new Notice()
                .setNoticeType(Const.NOTICE_TYPE_REPLY)
                .setRead("0")
                .setReceiveUserId(comments.getReplyUserId())
                .setSendUserId(comments.getUserId())
                .setText("回复你：" + comments.getText())
                .setCreateTime(new Date())
        );
        WebSocketServer.sendMessageToUser(comments.getReplyUserId(), new WebSocketMessage<>()
                .setData("回复你：" + comments.getText())
                .setType("string")
        );
        return Result.success("评论成功", null);
    }

    /**
     * 删除评论
     */
    @Override
    @Transactional
    public Result<String> deleteComment(Integer id) {

        //删除子评论下的喜欢记录
        //查找子评论ids
        try {
            List<Integer> list = commentMapper.selectReplyIds(id);
            System.out.println(list);
            for (Integer i : list) {
                likeRecordsMapper.deleteLikeRecordBase(new LikeRecords().setCommentId(i));
            }
        } catch (Exception e) {
            throw new MyException("删除子评论喜欢失败" + e);
        }

        //删除主评论喜欢
        try {
            likeRecordsMapper.deleteLikeRecordBase(new LikeRecords().setCommentId(id));
        } catch (Exception e) {
            throw new MyException("删除主评论喜欢失败" + e);
        }
        //删除子评论
        try {
            commentMapper.deleteReplyComment(id);
        } catch (Exception e) {
            throw new MyException("删除子评论失败" + e);
        }
        try {
            //删除主评论
            commentMapper.deleteComment(id);
        } catch (Exception e) {
            throw new MyException("删除主评论失败" + e);
        }
        return Result.success("删除成功", null);
    }

    @Override
    @Transactional
    public Result<String> deleteByArticleId(int id) {
        //TODO 删除评论
        try {
            commentMapper.deleteCommentByArticleId(id);
        } catch (Exception e) {
            throw new MyException("评论删除失败" + e);
        }

        return Result.success("删除成功", null);
    }
}
